package com.fkc.javahansoulbms.interceptor;


import com.fkc.javahansoulbms.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

// 登录拦截器
public class LoginInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = request.getHeader("Authorization");
		
		if (token == null || token.isEmpty()) {
			response.sendError(401, "未提供认证 Token");
			
			return false;
		}
		
		try {
			String userId = JwtUtils.parseToken(token);
			// 这里可以将用户信息存储到请求属性中，供后面使用
			request.setAttribute("userId", userId);
			
			return true;
		} catch (Exception e) {
			response.sendError(401, "无效的 Token：" + e.getMessage());
			return false;
		}
	}
}
